<?php

namespace app\admin\controller\auth;

use app\admin\controller\Base;
use app\admin\library\Tree;
use Cache;
use app\admin\validate\AuthRule;

/**
 * 规则管理
 *
 * @icon fa fa-list
 * @remark 规则通常对应一个控制器的方法,同时左侧的菜单栏数据也从规则中体现,通常建议通过控制台进行生成规则节点
 */
class Rule extends Base
{

    protected $model = null;
    protected $validate = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';

    public function initialize()
    {
        parent::_initialize();
        $this->model = model('AuthRule');
        $this->validate = validate('AuthRule');
        // 必须将结果集转换为数组
        $ruleList = collection($this->model->order('weigh', 'desc')->select())->toArray();
        // foreach ($ruleList as $k => &$v)
        // {
        //     $v['title'] = "标题";
        //     $v['remark'] = "备注";
        // }
        // unset($v);
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
        $ruledata = [0 => 'None'];
        foreach ($this->rulelist as $k => &$v)
        {
            if (!$v['ismenu'])
                continue;
            $ruledata[$v['id']] = $v['title'];
        }
        $this->view->assign('ruledata', $ruledata);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $list = $this->rulelist;
            if($this->request->get('t')=='one'){
                $result=$this->model->get(['id' => $this->request->get('ids')]);
            }else{
                $total = count($this->rulelist);

                $result = array("count" => $total, "data" => $list,'code'=>0);
            }
            

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                // halt($params);
                if (!$params['ismenu'] && !$params['pid'])
                {
                    $this->error("不是菜单的规则必须选择父节点");
                }
                // $result = $this->model->validate()->save($params);
                // $validate=new AuthRule() ;
                // if (!$validate->scene('edit')->check($params))
                // {
                //     $this->error($validate->getError());
                // }else{

                // }
                $result= $this->validate($params,'app\admin\validate\AuthRule.edit');
                if(true !== $result){
                    // 验证失败 输出错误信息
                    $this->error($result);
                }else{

                    $sa=$this->model->allowField(true)->save($params);
                    if(false===$sa){
                        $this->error($this->model->getError());
                    }else{

                        $this->success("添加成功！",url('edit','ids='.$this->model->id));
                    }
                }
                // Cache::rm('__menu__');
            }
            
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error("记录不存在");
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                if (!$params['ismenu'] && !$params['pid'])
                {
                    $this->error("不是菜单的规则必须选择父节点");
                }
                //这里需要针对name做唯一验证
                // $result= $this->validate($params,'app\admin\validate\AuthRule.edit');
                // $this->validate->rule([
                //     'name' => 'require|format|unique:AuthRule,name,' . $row->id,
                // ]);
                $result =$this->validate->check($params,['name' => 'require|format|unique:AuthRule,name,' . $row->id]);
                // $result = $row->validate()->save($params);
                if ($result === true)
                {
                    $res=$row->save($params);
                    if($res===false){

                        $this->error($this->getError());
                    }else{
                        $this->success("修改成功",url('edit',"ids=".$row->id));
                    }
                }else{
                    $this->error($result);
                }
                // Cache::rm('__menu__');
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $delIds = [];
            foreach (explode(',', $ids) as $k => $v)
            {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, TRUE));
            }
            $delIds = array_unique($delIds);
            $count = $this->model->where('id', 'in', $delIds)->delete();
            if ($count)
            {
                return json(['status'=>200]);
            }
        }
        return json(['status'=>400]);
    }

}
